package pers.karl.web.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Package: demo.karl.springboot.web.controller
 * @Description:
 * @Author: caoql
 * @Date: 2018/12/29 8:43
 * @version: V1.0
 */
@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * 用于查看请求信息
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/request")
    public Map<String, Object> receiveRequest(HttpServletRequest request) throws IOException {

        Map<String, Object> info = new HashMap<>();

        // 请求方法
        String method = request.getMethod();
        info.put("method", method);

        // 请求头
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String,String> headers = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headers.put(headerName, headerValue);
        }
        info.put("headers", headers);

        // url中的请求参数
        String queryString = request.getQueryString();
        if(StringUtils.hasText(queryString)) {
            info.put("queryString", URLDecoder.decode(queryString, StandardCharsets.UTF_8.name()));
        }

        // body中的请求参数
        try (BufferedReader reader = request.getReader()){
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            if(stringBuilder.length() > 0) {
                info.put("body", URLDecoder.decode(stringBuilder.toString(), StandardCharsets.UTF_8.name()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//        Map<String, String[]> parameterMap = request.getParameterMap();
//        info.put("parameterMap", parameterMap);

        return info;
    }

}
